<template>
  <div class="update-pwd">
    <van-nav-bar
      title="修改密码"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
    />
    <div class="container">
      <div class="form">
        <van-form ref="form">
          <van-cell-group inset class="item">
            <van-field
              v-model="oldPwd"
              placeholder="请输入旧密码"
              clearable
              inset
              :type="showPwd ? 'text' : 'password'"
              right-icon="eye-o"
              @click-right-icon="showPwd = !showPwd"
              :rules="[{ required: true, message: '请输入旧密码' }]"
            />
          </van-cell-group>
          <van-cell-group inset class="item">
            <van-field
              v-model="newPwd"
              placeholder="请输入新密码"
              clearable
              inset
              type="password"
              :rules="[{ required: true, message: '请输入新密码' }]"
            />
          </van-cell-group>
          <van-cell-group inset class="item">
            <van-field
              v-model="verifyPwd"
              placeholder="确认新密码"
              clearable
              inset
              type="password"
              :rules="[
                { required: true, message: '请确认新密码' },
                {
                  validator: (val) => val === newPwd,
                  message: '两次密码不一致',
                },
              ]"
            />
          </van-cell-group>
          <van-cell-group inset class="item">
            <van-button type="info" block @click="updatePwd"
              >修改密码</van-button
            >
          </van-cell-group>
        </van-form>
      </div>
    </div>
  </div>
</template>

<script>
import { updatePwd, verifyPwd } from "@/api/mobile/user";
import modifyActivityTime from "@/utils/modify";
import userModule from "@/utils/userInfo";
import { Notify } from "vant";

export default {
  name: "UpdatePwdView",
  data() {
    return {
      oldPwd: "",
      newPwd: "",
      verifyPwd: "",
      showPwd: false,
    };
  },
  created() {
    modifyActivityTime();
  },
  methods: {
    // 修改密码
    async updatePwd() {
      await this.$refs.form.validate();
      const user = userModule.getUser();
      // 校验密码
      await verifyPwd({
        id: user.id,
        password: this.oldPwd,
      });
      // 修改密码
      await updatePwd({
        id: user.id,
        password: this.newPwd,
      });
      // 清空缓存
      userModule.setUser(null);
      localStorage.removeItem("u_t");
      // 跳转登录页
      Notify({ type: "success", message: "请重新登陆" });
      this.$router.push("/login");
    },
  },
};
</script>

<style lang="less" scoped>
.update-pwd {
  height: 100vh;
  background-color: rbg(247, 248, 250);
  .container {
    padding: 0 30px;
    .item {
      margin: 20px 0;
    }
  }
}
</style>